package sivan.process;

import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;
import sivan.domain.Student;

/**
 * Created by sivan on 2019/2/25.
 * 可以让我们实现自定义的注册bean定义的逻辑
 * 在refresh()的invokeBeanFactoryPostProcessors方法调用
 *
 * 实现Ordered与实现PriorityOrdered的区别：
 * 1 实现这两种方式可以更改BeanDefinitionRegistryPostProcessor优先级，PriorityOrdered > Ordered
 * 2 当两个BeanDefinitionRegistryPostProcessor都实现了相同的Ordered或者PriorityOrdered时候，getOrder返回值越小优先级别越高
 */
@Component
public class CustomBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor,PriorityOrdered {

    /**
     * 手动定义bean的定义
     * @param registry
     * @throws BeansException
     */
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        RootBeanDefinition studentBean = new RootBeanDefinition(Student.class);
        MutablePropertyValues value = new MutablePropertyValues();
        value.add("name","yqq");
        value.add("age",23);
        value.add("grade",9);
        studentBean.setPropertyValues(value);
        registry.registerBeanDefinition("student",studentBean);
        System.out.println("执行了postProcessBeanDefinitionRegistry方法注册了Student对象=======");
    }

    /**
     * 对手动定义的bean定义完之后，bean实例之前进行操作
     * @param beanFactory
     * @throws BeansException
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("实现了CustomBeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法");
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
